package com.geeguo.ebuilder.core.feign.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;

/**
 * 开发环境负载均衡配置
 */
@Slf4j
@Configuration
@LoadBalancerClients(defaultConfiguration = LoadBalancerConfig.class)
public class LoadBalancerConfig {

    @Autowired
    private InetUtils inetUtils;

    @Bean
    @ConditionalOnProperty(value = "spring.profiles.active", havingValue = "dev")
    ReactorLoadBalancer<ServiceInstance> devLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        InetAddress firstNonLoopbackAddress = inetUtils.findFirstNonLoopbackAddress();
        return new LocalPriorityLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name, firstNonLoopbackAddress.getHostAddress());
    }

    @Bean
    @LoadBalanced
    @ConditionalOnProperty(value = "spring.profiles.active", havingValue = "dev")
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
